//
//  SearchViewController.m
//  BaiTuan
//
//  Created by huiwenjiaoyu on 15/12/23.
//  Copyright © 2015年 YR. All rights reserved.
//

#import "SearchViewController.h"
#import "AppDelegate.h"
#import "ShopsModel.h"
#import "SearchResultViewController.h"
#import "SearchListController.h"


@interface SearchViewController ()

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *shopArray;
@property (nonatomic, strong) UISearchBar *search;
@property (nonatomic, strong) SearchListController *searchList;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self createView];
}

-(void)viewDidAppear:(BOOL)animated
{
    _search.hidden = NO;
    [_search becomeFirstResponder];
}

- (void)createView
{
    _search = [[UISearchBar alloc]initWithFrame:CGRectMake(60, -10, kScreenWidth - 120, 64)];
    [self.navigationController.navigationBar addSubview:_search];
    _search.layer.cornerRadius = 10;
    _search.searchBarStyle = UISearchBarStyleMinimal;
    _search.delegate = self;
    _search.keyboardType = UIKeyboardTypeDefault;
    _search.placeholder = @"请输入商家名、品类或商圈...";
    
    UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 25, 25)];
    [backButton addTarget:self action:@selector(popAction:) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:[UIImage imageNamed:@"btn_backItem.png"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_backItem_highlighted.png"] forState:UIControlStateHighlighted];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:(UIView *)backButton];
    self.navigationItem.leftBarButtonItem = barButton;
    
    self.view.backgroundColor = [UIColor orangeColor];
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:45 / 255.0    green:177 / 255.0 blue:157 / 255.0 alpha:1];

}

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"normalCell"];
    }
    return _tableView;
}


- (void)popAction:(UIButton *)button
{
    _search.hidden = YES;
    [self.navigationController popToRootViewControllerAnimated:YES];
    [_search resignFirstResponder];
    
}

#pragma mark - 网络请求

-(void)requestShopData:(CLLocation *)location shopName:(NSString *)shopName
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer setValue:apikey forHTTPHeaderField:@"apikey"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    
    NSString *locationStr = [NSString stringWithFormat:@"%f,%f",location.coordinate.longitude,location.coordinate.latitude];
    
    [params setObject:shopName forKey:@"keyword"];
    [params setObject:locationStr forKey:@"location"];
    [params setObject:@600010000 forKey:@"city_id"];
    
    
    [manager GET:shop_city parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self loadShopData:responseObject];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@", error);
    }];
    
}

- (void)loadShopData:(NSDictionary *)dic
{
    if (dic[@"data"] != [NSNull null])
    {
        NSDictionary *data = dic[@"data"];
        NSArray *shops = data[@"shops"];
        
        _shopArray = [[NSMutableArray alloc]init];
        for (NSDictionary *shopDic in shops) {
            
            ShopsModel *shopModel = [[ShopsModel alloc]initContentWithDic:shopDic];
            
            [_shopArray addObject:shopModel];
        }
        
        _searchList = [[SearchListController alloc]init];
        _searchList.dataArray = _shopArray;
        [_tableView reloadData];
        
    }

}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _shopArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"normalCell" forIndexPath:indexPath];
    
    ShopsModel *shop = _shopArray[indexPath.row];
    cell.textLabel.text = shop.shop_name;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchResultViewController *resultVC = [[SearchResultViewController alloc]init];
//    self.block(_search.text);
    [self.navigationController pushViewController:resultVC animated:YES];
    [_search resignFirstResponder];
    _search.hidden = YES;
//    ShopsModel *shop = _shopArray[indexPath.row];
}



#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    _search.showsCancelButton = YES;
    self.tableView.hidden = NO;
    
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    self.tableView.hidden = YES;
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [_search resignFirstResponder];
    self.tableView.hidden = YES;
    _search.showsCancelButton = NO;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [self requestShopData:delegate.userLocation shopName:searchText];
    
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    _search.hidden = YES;
    [_search resignFirstResponder];
    [self.navigationController pushViewController:_searchList animated:YES];
    
}


@end
